<template>
  <div>
    <div style="position: fixed; top: 0; left: 0; right: 0;
                height: 80px; width: 100vw; background-color: #2c82ff; z-index: 1000;">
      <div style="display: flex;justify-content: space-between;align-items: center;">
        <div style="width: 240px;display: flex;align-items: center;">
          <span style="padding-left: 15px;font-size: 20px;font-weight: bold;color: #fff;">ExpressEasy</span>
        </div>
        <div style="display: flex;align-items: center;padding: 10px" @click="router.push('/mobilePerson')">
          <img v-if="data.user?.avatar" style="width: 50px; height: 50px;border-radius: 50%" :src="data.user?.avatar" alt="">
          <img v-else style="width: 50px; height: 50px;border-radius: 50%" src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" alt="">
        </div>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content-wrapper">
      <el-card class="scanner-card">
        <div class="scanner-container">
          <qrcode-stream 
            v-if="data.showScanner"
            @decode="onScan"
            :camera="data.cameraStatus"
            class="scanner"
            style="width: 80vw; height: 80vw"
          >
            <div class="scan-overlay">
              <div class="scan-frame"></div>
              <span class="scan-tip">将快递单号二维码放入框内扫描</span>
            </div>
          </qrcode-stream>

          <!-- 扫描结果弹窗 -->
          <el-dialog 
            v-model="data.resultDialog" 
            title="扫描结果" 
            width="90%"
            :show-close="false"
          >
            <el-descriptions :column="1" border>
              <el-descriptions-item label="快递单号">{{ data.scanResult.trackingNumber }}</el-descriptions-item>
              <el-descriptions-item label="当前状态">{{ data.scanResult.state }}</el-descriptions-item>
              <el-descriptions-item label="取件码">
                <el-tag type="success">{{ data.scanResult.pickupCode || '生成中...' }}</el-tag>
              </el-descriptions-item>
            </el-descriptions>
            
            <template #footer>
              <el-button @click="resetScanner">继续扫描</el-button>
              <el-button type="primary" @click="copyPickupCode">复制取件码</el-button>
            </template>
          </el-dialog>

          <!-- 手动输入备用 -->
          <div class="manual-input">
            <el-input
              v-model="data.manualNumber"
              placeholder="请输入快递单号"
              clearable
              @keyup.enter="handleManualInput"
            >
              <template #append>
                <el-button @click="handleManualInput">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
          </div>
        </div>
      </el-card>
    </div>
    <!-- 底部区域开始 -->
    <div style=" position: fixed; bottom: 0; left: 0; right: 0;
                 height: 55px; background-color: #2c82ff; z-index: 1000;">
      <div style="height: 100%; display: flex; justify-content: space-around; align-items: center;">
        <div style="color: #ffd04b; display: flex; flex-direction: column; align-items: center;">
          <el-icon size="25"><HomeFilled /></el-icon>
          首页
        </div>
        <div style="color: white; display: flex; flex-direction: column; align-items: center;" @click="router.push('/mobilePerson')">
          <el-icon size="25"><UserFilled /></el-icon>
          个人中心
        </div>
      </div>
    </div>
    <!-- 底部区域结束 -->
  </div>
</template>

<script setup>
// noinspection ES6UnusedImports
import {QrcodeStream} from "vue-qrcode-reader";
import {reactive} from 'vue'
import {ElMessage} from 'element-plus'
import request from "@/utils/request.js"
import router from "@/router/index.js";

// 响应式数据对象
const data = reactive({
  user: JSON.parse(localStorage.getItem('code_user') || "{}"), // 从本地存储获取用户信息
  showScanner: true,    // 控制扫描器显示
  cameraStatus: 'auto', // 摄像头状态（auto/off）
  resultDialog: false,  // 结果弹窗显示控制
  scanResult: {},       // 扫描结果存储
  manualNumber: ''      // 手动输入的单号
})


/**
 * 处理扫描结果
 * @param {string} trackingNumber - 扫描获得的快递单号
 */
const onScan = async (trackingNumber) => {
  try {
    data.cameraStatus = 'off' // 扫描成功后关闭摄像头
    // 调用后端接口处理扫描结果
    const res = await request.post('/package/scan-process', {
      trackingNumber,
      state: '待签收'
    })

    // 更新扫描结果
    data.scanResult = {
      trackingNumber,
      state: '待签收',
      pickupCode: res.data?.pickupCode
    }
    data.resultDialog = true // 显示结果弹窗
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '操作失败')
    resetScanner()
  }
}

// 重置扫描器状态
const resetScanner = () => {
  data.showScanner = true
  data.cameraStatus = 'auto'
  data.resultDialog = false
  data.scanResult = {}
  data.manualNumber = ''
}

// 处理手动输入快递单号
const handleManualInput = () => {
  if (!data.manualNumber) return
  onScan(data.manualNumber)
}

// 复制取件码到剪贴板
const copyPickupCode = () => {
  navigator.clipboard.writeText(data.scanResult.pickupCode)
  ElMessage.success('取件码已复制')
}
</script>

<style scoped>
.content-wrapper{
  margin-top: 120px;
}

.scanner-card {
  margin: 20px;
  min-height: 70vh;
  display: flex;
  flex-direction: column;
}

.scanner-container {
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 70vh;
}

.scan-overlay {
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.scan-frame {
  border: 3px solid #2c82ff;
  height: 80vw;
  width: 80vw;
  box-shadow: 0 0 20px rgba(44, 130, 255, 0.3);
}

.scan-tip {
  position: absolute;
  display: block;
  text-align: center;
  color: #2c82ff;
  margin-top: 20px;
  font-weight: bold;
}

.manual-input {
  margin-top: 30px;
  padding: 0 15px;
}

</style>
